package smartt.styy.auth.util;

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;

import org.springframework.stereotype.Component;

@Component
public class DESEncrypt {
	private static String Algorithm = "desede/CBC/PKCS5Padding"; // 定义 加密算法,可用DES,DESede,Blowfish
	// 向量
	private static String iv = "01234567";
	private static String encoding = "utf-8";

	/**
	 * 3DES加密
	 * 
	 * @param plainText
	 *            普通文本
	 * @return
	 * @throws Exception
	 */
	public static String encryptMode(String secretKey, String plainText)
			throws Exception {
		Key deskey = null;
		try {
			DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
			SecretKeyFactory keyfactory = SecretKeyFactory
					.getInstance("desede");
			deskey = keyfactory.generateSecret(spec);
			Cipher cipher = Cipher.getInstance(Algorithm);
			IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
			cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
			byte[] encryptData = cipher.doFinal(plainText.getBytes(encoding));
			return Base64.encode(encryptData);
		} catch (Exception e) {
			throw e;
		}
	}

	/**
	 * 3DES解密
	 * 
	 * @param encryptText
	 *            加密文本
	 * @return
	 * @throws Exception
	 */
	public static String decryptMode(String secretKey, String encryptText)
			throws Exception {
		Key deskey = null;
		try {
			DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
			SecretKeyFactory keyfactory = SecretKeyFactory
					.getInstance("desede");
			deskey = keyfactory.generateSecret(spec);
			Cipher cipher = Cipher.getInstance(Algorithm);
			IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
			cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
			byte[] decryptData = cipher.doFinal(Base64.decode(encryptText));
			return new String(decryptData, encoding);
		} catch (Exception e) {
			throw e;
		}

	}

	public static void main(String args[]) throws Exception {
		String kekStr = "0123456789abcd0123456789"; 

		String minKey = "1qessdas4";
		String encMerKey = DESEncrypt.encryptMode(kekStr, minKey); // 加密得到密文key
		System.out.println("加密密钥密文=" + encMerKey);
		
		encMerKey = "qjIl0J4JoU8xKfb4c4k9cg==";
		String xx = DESEncrypt.decryptMode(kekStr, encMerKey); // 解密得到明文key
		System.out.println("解密密钥明文=" + xx);

		
		
		
	}
}
